//
//  ChatWindowController.mm
//  Ta
//
//  Created by Sangeun Kim on 3/13/11.
//  Copyright 2011 NHN Corporation. All rights reserved.
//

#import "ChatWindowController.h"
#import "ChatTextFieldCell.h"
#import "RowResizableTableView.h"
#import "XMPPSession.h"
#import "MessageItem.h"

@implementation ChatWindowController
@synthesize targetImage;
@synthesize myImage;
@synthesize targetJid;
@synthesize targetName;
@synthesize session;

- (void)applicationDidBecomeActive:(NSNotification *)aNotification
{
	if (![[self window] isVisible]) {

	}
    else {
        [[self window] makeKeyAndOrderFront:self];
    }
    [[NSNotificationCenter defaultCenter]postNotificationName:@"readMessage" object:self];
}

-(BOOL)applicationShouldHandleReopen:(NSApplication *)theApplication
				   hasVisibleWindows:(BOOL)flag
{
    [[NSNotificationCenter defaultCenter]postNotificationName:@"readMessage" object:self];
	return YES;
}

- (void)windowWillClose:(NSNotification *)notification
{
    [session close];
}

- (void)windowDidClose:(NSNotification *)notification
{
}

- (BOOL)windowShouldClose:(id)sender
{
	return YES;
}

- (void) setTargetJid:(NSString *)_targetJid
{
    [targetJid release];
    targetJid = _targetJid;
    [targetJidField setStringValue:targetJid];
}

- (void) setTargetName:(NSString *)_targetName
{
    [targetName release];
    targetName = _targetName;
    
    [[self window]setTitle:[NSString stringWithFormat:@"Conversation - %@", targetName]];
    [targetNameField setStringValue:targetName];
}

- (void) setTargetImage:(NSImage *)image
{
    if (targetImage == image) {
        return;
    }
    [profileImageView setImage:image];
    [targetImage release];
    targetImage = [image retain];
}

- (void) awakeFromNib
{
	messageArray = [[NSMutableArray alloc] init] ;//]arrayWithCapacity:1000];

	[chatListCtrl setDataSource:self];
	[chatListCtrl setDelegate:self];
    [chatListCtrl setDoubleAction:@selector(onDoubleClick:)];
    [chatListCtrl setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone];
	[chatListCtrl setIntercellSpacing:NSMakeSize(0,0)]; 
}

- (void)dealloc
{
    
/*    NSEnumerator* e = [messageArray objectEnumerator];
    MessageItem* item;
    while (nil != (item = [e nextObject])) {
        [item release];
    }*/
    [messageArray removeAllObjects];
	[messageArray release];
    
    [targetImage release];
    [super dealloc];
}

-(BOOL)addMessageItem:(MessageItem*)item
{
    [messageArray addObject:item];
    [chatListCtrl reloadData];
    [chatListCtrl scrollRowToVisible:[messageArray count]];
    return YES;
    
}

-(void)onMessageReceived:(MessageItem*)msg;
{
    [self addMessageItem:msg];
}

-(IBAction)send:(id)sender
{
	if (!msgToSend) {
		return;
	}

	if (![[msgToSend stringValue]length]) {
		return;
	}
	
    NSMapTable *emojiMap = [NSMapTable mapTableWithStrongToStrongObjects];
    
    [emojiMap setObject:@"E056" forKey:@":)"];
    [emojiMap setObject:@"E057" forKey:@":D"];
    [emojiMap setObject:@"E058" forKey:@":("];
    [emojiMap setObject:@"E059" forKey:@":<"];
    [emojiMap setObject:@"E40B" forKey:@":o"];
    [emojiMap setObject:@"E40D" forKey:@":|"];
    [emojiMap setObject:@"E40E" forKey:@";<"];
    
    
    NSMutableString* message = [[NSMutableString alloc]initWithString:[msgToSend stringValue]];
    NSEnumerator* e = [emojiMap keyEnumerator];
    NSString* strEmoticon;
    while (nil != (strEmoticon = [e nextObject])) {
        NSRange range = [message rangeOfString:strEmoticon];
        if (range.location == NSNotFound) {
            continue;
        }
        NSScanner* emoScanner = [NSScanner scannerWithString:[emojiMap objectForKey:strEmoticon]];
        unsigned int intEmo;
        [emoScanner scanHexInt:&intEmo];
        unichar chEmo = intEmo;
        NSString* emoCode = [NSString stringWithCharacters:&chEmo length:1];
        do {
            [message replaceCharactersInRange:range withString:emoCode];
            range = [message rangeOfString:strEmoticon];
        }
        while ( range.location != NSNotFound );
    }
    
    MessageItem* item = [[MessageItem alloc]init];
    [item setJid:@""];
    [item setMessage:message];
    [item setTimeStamp:[NSDate date]];
    [session sendMessage:item];
    [self addMessageItem:item];
    [item release];    
	
	[msgToSend setStringValue:@""];
}

- (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
{
	return [messageArray count];
}

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
	MessageItem* item = [messageArray objectAtIndex:rowIndex];
	if ([[aTableColumn identifier]isEqualToString:@"ProfileImage"]) {
		if ([[item jid]isEqualToString:targetJid]) {
			return targetImage;
		}
		else {
			return nil;
		}
	}
    else if ([[aTableColumn identifier]isEqualToString:@"MyImage"]) {
		if ([[item jid]isEqualToString:@""]) {
			return myImage;
		}
		else {
			return nil;
		}
        
    }
	if ([[aTableColumn identifier]isEqualToString:@"TextMessage"]) {
		if ([[item jid]isEqualToString:@""]) {
			[[aTableColumn dataCell]setLeftArrow:NO];
			
		}
		else {
			[[aTableColumn dataCell]setLeftArrow:YES];
		}
        if ([item timeStamp]) {
            [[aTableColumn dataCell]
             setMessageTime:[item timeStamp]];
        }
		if (rowIndex == [aTableView selectedRow]) {
			[[aTableColumn dataCell] setSelected:YES];
		}
		else {
			[[aTableColumn dataCell] setSelected:NO];
		}
        
//        [[aTableColumn dataCell] setIsAck:[item isAck]];
//        [[aTableColumn dataCell] setIsSucceeded:[item isSucceeded]];

		return [item message];
	}
	return @"";
    
}

- (IBAction)    copy:(id) sender
{
    NSInteger index = [chatListCtrl selectedRow];
    if (index == -1) {
        return;
    }
    
    MessageItem* item = [messageArray objectAtIndex:index];
    NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
    

    [pasteboard clearContents];
    [pasteboard setString: [item message] forType:NSStringPboardType];
    
}

- (IBAction) onDoubleClick:(id)sender
{
//    NSText *textEditor;
    NSInteger index = [sender selectedRow];
    
    [sender editColumn:1 row:index withEvent:nil select:YES];

}

- (void)tableView:(NSTableView *)aTableView willDisplayCell:(id)aCell forTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex
{
    if (![aCell isKindOfClass:[ChatTextFieldCell class]])
    {
        return;
    }
	if ([(RowResizableTableView*)aTableView mouseOverRow] == rowIndex)
    {
		[aCell onMouseEnter];// NSLog(@"%d could be highlighted", rowIndex);
    }
	else {
        [aCell onMouseEnter]; 
    }//NSLog(@"%d shouldn't be highlighted", rowIndex);
}
@end
